#include "StdAfx.h"
#include "Pmxy.h"
#include <mshtml.h>
#include <mshtmdid.h>
#include <exdispid.h>
#include <exdisp.h>
#include <atlbase.h>
#include <atlWin.h>

CPmxy::CPmxy(void)
{	
}

CPmxy::~CPmxy(void)
{
}

// http://www.4399.com/
// http://my.4399.com/app_pm.html
// http://my.4399.com/webgame.php?game=pm&act=go&server=1
bool CPmxy::LoginPM(IHTMLDocument2 *pHtmlDoc, LPTSTR pszUserName, LPTSTR pszPW)
{
	if ( pHtmlDoc == NULL )
	{
		return false;
	}

	HRESULT hr;

	//
	// user name
	//
	CComPtr<IHTMLDocument3> spHtmlDoc3;
	CComPtr<IHTMLElementCollection> spelColUserName;
	hr = pHtmlDoc->QueryInterface(IID_IHTMLDocument3, (void**)&spHtmlDoc3);
	hr = spHtmlDoc3->getElementsByName(L"username", &spelColUserName);

	long elUserNameNumber = 0;
	hr = spelColUserName->get_length(&elUserNameNumber);
	if ( elUserNameNumber < 1 )
	{
		return false;
	}

	bool bSuccess = false;
	for ( int index = 0; index < elUserNameNumber; ++index )
	{
		CComVariant varIndex(index);
		CComPtr<IDispatch> spdispUserName;
		hr = spelColUserName->item(varIndex, varIndex, &spdispUserName);
		if ( FAILED(hr) )
		{
			continue;
		}

		CComPtr<IHTMLInputElement> spInput;
		hr = spdispUserName->QueryInterface(IID_IHTMLInputElement, (void**)&spInput);
		if ( FAILED(hr) || spInput == NULL )
		{
			continue;
		}

		spInput->put_value(/*L"1513697909"*/pszUserName);	
		bSuccess = true;
	}
	
	if ( !bSuccess )
	{
		return false;
	}

	//
	// password
	//
	CComPtr<IHTMLElementCollection> spelColPasswd;
	hr = spHtmlDoc3->getElementsByName(L"password", &spelColPasswd);
	
	long elPasswdNumber = 0;
	hr = spelColPasswd->get_length(&elPasswdNumber);
	if ( elPasswdNumber < 1 )
	{
		return false;
	}

	bSuccess = false;
	for ( int index = 0; index < elPasswdNumber; ++index )
	{
		CComVariant varIndex(index);
		CComPtr<IDispatch> spdispPasswd;
		hr = spelColPasswd->item(varIndex, varIndex, &spdispPasswd);
		if ( FAILED(hr) )
		{
			continue;
		}

		CComPtr<IHTMLInputElement> spInput;
		hr = spdispPasswd->QueryInterface(IID_IHTMLInputElement, (void**)&spInput);
		if ( FAILED(hr) || spInput == NULL )
		{
			continue;
		}

		spInput->put_value(/*L"itosikute"*/pszPW);	

		//
		// submit
		//
		CComPtr<IHTMLFormElement> spForm;
		hr = spInput->get_form(&spForm);
		//hr = spForm->submit();
		bSuccess = true;
	}	
	
	return true;
}


void CPmxy::SetBrowserStyle(IHTMLDocument2* spDoc)
{
	HRESULT hr = E_FAIL;
	CComPtr<IHTMLElement> spEleBody;
	CComPtr<IHTMLElement> spEleHtml;
	CComPtr<IHTMLStyle>  spStyleHtml;

	hr = spDoc->get_body(&spEleBody);
	hr = spEleBody->get_parentElement(&spEleHtml);
	hr = spEleHtml->get_style(&spStyleHtml);
	hr = spStyleHtml->put_overflow(L"hidden");	
	//hr = spStyleHtml->put_background(L"red");
}

